<template>
<div>
<div class="search">
 <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音"/>
</div>
 <div class="search-content" ref="search" v-show="keyword">
  <ul>
   <li class="search-item" v-for="(item, index) of list" :key="index" @click="handleCityClick(item)">{{item}}</li>
   <li class="search-item" v-show="noCity">没有您想要找的城市</li>
  </ul>
 </div>
</div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'

export default {
  name: 'CitySearch',
  props: ['cities'],
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])// 简化代码 不用写成 this.$store.commit
  },
  computed: {
    noCity () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const i in this.cities) {
          console.log(this.cities[i].lists)
          this.cities[i].lists.forEach((value) => {
            if (value.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}

</script>

<style lang="stylus" scoped>
@import '~@/assets/style/varibles.styl'
.search
 height : 2.5rem
 padding : 0.2rem
 background : $bgColor
 .search-input
  box-sizing : border-box
  width : 100%
  height : 2.5rem
  line-height : 1rem
  text-align : center
  border-radius : 0.5rem
  color : #666
.search-content
 z-index :1
 overflow :hidden
 position :absolute
 top :5.9rem
 left :0
 right :0
 bottom :0
 background : #EEE
 .search-item
  line-height :2rem
  padding-left :1rem
  color :#666
  background :#fff
  border-bottom :1px solid #ccc
</style>
